package web;

import api.CollectionManager;
import api.DatabaseManager;
import api.Match;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.basex.core.BaseXException;

/**
 *
 * @author Football-Statistics Team
 */
public class EditMatchServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Locale locale = request.getLocale();
        ResourceBundle labelsBundle;
        labelsBundle = ResourceBundle.getBundle("labelsBundle", locale);

        String lid = request.getParameter("lid");
        String mid = request.getParameter("mid");
        request.setAttribute("lid", lid);
        request.setAttribute("mid", mid);
        
        DatabaseManager dm = new DatabaseManager();
        CollectionManager cm = new CollectionManager(lid, dm);
        try {
            request.setAttribute("xml_leagues", cm.getLeagueList());
            request.setAttribute("xml_matches", cm.getMatchList());
            if (mid != null && !mid.equals("")) {
                request.setAttribute("xml_match",cm.getMatch(mid));            
            }
            request.getRequestDispatcher("/editMatch.jsp").forward(request, response);
            return;
        } catch (BaseXException ex) {
            Logger.getLogger(EditMatchServlet.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", labelsBundle.getString("database_error"));
            request.getRequestDispatcher("/editMatch.jsp").forward(request, response);
            return;
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Locale locale = request.getLocale();
        ResourceBundle labelsBundle;
        labelsBundle = ResourceBundle.getBundle("labelsBundle", locale);

        int round, score_full_home, score_full_guests, score_half_home, score_half_guests;
        int goals_home_num, goals_guests_num, cards_home_num, cards_guests_num, min;
        int changes_home_num, changes_guests_num, players_home_num, players_guests_num, spectators;
        String lid, mid, league, season, date, time, referee, stadium, home, guests, player, in, out, type;
        
        //get league list, match list and old match data
        lid = request.getParameter("lid");
        mid = request.getParameter("mid");
        request.setAttribute("lid", lid);
        request.setAttribute("mid", mid);
        DatabaseManager dm = new DatabaseManager();
        CollectionManager cm = new CollectionManager(lid, dm);
        try {
            request.setAttribute("xml_leagues", cm.getLeagueList());
            request.setAttribute("xml_matches", cm.getMatchList());
            if (mid != null && !mid.equals("")) {
                request.setAttribute("xml_match",cm.getMatch(mid));            
            }
        } catch (BaseXException ex) {
            Logger.getLogger(EditMatchServlet.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", labelsBundle.getString("database_error"));
            request.getRequestDispatcher("/editMatch.jsp").forward(request, response);
            return;
        }
        
        //static number parameters check
        try {
            round = Integer.parseInt(request.getParameter("round"));
            score_full_home = Integer.parseInt(request.getParameter("score_full_home"));
            score_full_guests = Integer.parseInt(request.getParameter("score_full_guests"));
            score_half_home = Integer.parseInt(request.getParameter("score_half_home"));
            score_half_guests = Integer.parseInt(request.getParameter("score_half_guests"));       
            goals_home_num = Integer.parseInt(request.getParameter("goals_home_num"));
            goals_guests_num = Integer.parseInt(request.getParameter("goals_guests_num"));
            cards_home_num = Integer.parseInt(request.getParameter("cards_home_num"));
            cards_guests_num = Integer.parseInt(request.getParameter("cards_guests_num"));
            changes_home_num = Integer.parseInt(request.getParameter("changes_home_num"));
            changes_guests_num = Integer.parseInt(request.getParameter("changes_guests_num"));
            players_home_num = Integer.parseInt(request.getParameter("players_home_num"));
            players_guests_num = Integer.parseInt(request.getParameter("players_guests_num"));
            spectators = Integer.parseInt(request.getParameter("spectators"));
        } catch (IllegalArgumentException ex) {
            request.setAttribute("error", labelsBundle.getString("illegal_parameter"));
            request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
            return;
        }
        //static string parameters check
        league = request.getParameter("league");
        season = request.getParameter("season");        
        date = request.getParameter("date");
        time = request.getParameter("time");
        home = request.getParameter("home");
        guests = request.getParameter("guests");
        referee = request.getParameter("referee");
        stadium = request.getParameter("stadium");       
        if (lid == null || lid.equals("") || mid == null || mid.equals("") ||
        league == null || league.equals("") || season == null || season.equals("") ||
        date == null || date.equals("") || time == null || time.equals("") ||
        home == null || home.equals("") || guests == null || home.equals("") ||
        referee == null || referee.equals("") || stadium == null || stadium.equals("")) {
            request.setAttribute("error", labelsBundle.getString("parameters_not_set"));
            request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
            return;            
        }
        //add static parameters to match
        Match match = new Match();
        match.setId(mid);
        match.setLeague(league);
        match.setSeason(season);
        match.setScore(score_half_home, score_half_guests, score_full_home, score_full_guests);
        match.setDate(date);
        match.setTime(time);
        match.setHome(home);
        match.setGuests(guests);
        match.setRound(round);
        match.setReferee(referee);
        match.setStadium(stadium);
        match.setSpectators(spectators);
        
        //dynamic parameters
        
        //check and add goals
        for (int i = 0; i < goals_home_num; i++) {
            try {
                min = Integer.parseInt(request.getParameter("goals_home_minute_" + i));
            } catch (IllegalArgumentException ex) {
                request.setAttribute("error", labelsBundle.getString("illegal_parameter"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;
            }
            player = request.getParameter("goals_home_player_" + i);
            if (player == null || player.equals("")) {
                request.setAttribute("error", labelsBundle.getString("parameters_not_set"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;            
            }
            match.addGoal(1, min, player);
        }
        for (int i = 0; i < goals_guests_num; i++) {
            try {
                min = Integer.parseInt(request.getParameter("goals_guests_minute_" + i));
            } catch (IllegalArgumentException ex) {
                request.setAttribute("error", labelsBundle.getString("illegal_parameter"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;
            }
            player = request.getParameter("goals_guests_player_" + i);
            if (player == null || player.equals("")) {
                request.setAttribute("error", labelsBundle.getString("parameters_not_set"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;
            }
            match.addGoal(2, min, player);
        }
        //check and add cards
        for (int i = 0; i < cards_home_num; i++) {
            try {
                min = Integer.parseInt(request.getParameter("cards_home_minute_" + i));
            } catch (IllegalArgumentException ex) {
                request.setAttribute("error", labelsBundle.getString("illegal_parameter"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;
            }
            type = request.getParameter("cards_home_type_" + i);
            player = request.getParameter("cards_home_player_" + i);
            if (player == null || player.equals("") || type == null || type.equals("")) {
                request.setAttribute("error", labelsBundle.getString("parameters_not_set"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;            
            }
            match.addCard(1, min, type, player);
        }
        for (int i = 0; i < cards_guests_num; i++) {
            try {
                min = Integer.parseInt(request.getParameter("cards_guests_minute_" + i));
            } catch (IllegalArgumentException ex) {
                request.setAttribute("error", labelsBundle.getString("illegal_parameter"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;
            }
            type = request.getParameter("cards_guests_type_" + i);
            player = request.getParameter("cards_guests_player_" + i);
            if (player == null || player.equals("") || type == null || type.equals("")) {
                request.setAttribute("error", labelsBundle.getString("parameters_not_set"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;            
            }
            match.addCard(2, min, type, player);
        }
        //check and add changes
        for (int i = 0; i < changes_home_num; i++) {
            try {
                min = Integer.parseInt(request.getParameter("changes_home_minute_" + i));
            } catch (IllegalArgumentException ex) {
                request.setAttribute("error", labelsBundle.getString("illegal_parameter"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;
            }
            in = request.getParameter("changes_home_in_" + i);
            out = request.getParameter("changes_home_out_" + i);
            if (in == null || in.equals("") || out == null || out.equals("")) {
                request.setAttribute("error", labelsBundle.getString("parameters_not_set"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;            
            }
            match.addChange(1, min, in, out);
        }
        for (int i = 0; i < changes_guests_num; i++) {
            try {
                min = Integer.parseInt(request.getParameter("changes_guests_minute_" + i));
            } catch (IllegalArgumentException ex) {
                request.setAttribute("error", labelsBundle.getString("illegal_parameter"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;
            }
            in = request.getParameter("changes_guests_in_" + i);
            out = request.getParameter("changes_guests_out_" + i);
            if (in == null || in.equals("") || out == null || out.equals("")) {
                request.setAttribute("error", labelsBundle.getString("parameters_not_set"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;            
            }
            match.addChange(2, min, in, out);
        }
        //check and add players
        for (int i = 0; i < players_home_num; i++) {
            player = request.getParameter("players_home_player_" + i);
            if (player == null || player.equals("")) {
                request.setAttribute("error", labelsBundle.getString("parameters_not_set"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;            
            }
            match.addPlayer(1, player);
        }
        for (int i = 0; i < players_guests_num; i++) {
            player = request.getParameter("players_guests_player_" + i);
            if (player == null || player.equals("")) {
                request.setAttribute("error", labelsBundle.getString("parameters_not_set"));
                request.getRequestDispatcher("/editMatch.jsp").forward(request, response);            
                return;            
            }
            match.addPlayer(2, player);
        }
        
        //edit match
        try {
            cm.updateMatch(mid, match.getXML());
            request.setAttribute("xml_match",cm.getMatch(mid));//get new match data if no error occurs
        } catch (BaseXException ex) {
            Logger.getLogger(EditMatchServlet.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", labelsBundle.getString("database_error"));
            request.getRequestDispatcher("/editMatch.jsp").forward(request, response);
            return;
        }
        
        request.setAttribute("success", labelsBundle.getString("match_edited"));
        request.getRequestDispatcher("/editMatch.jsp").forward(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
